﻿using AntdUI;
using BST250301TestStand.Models;
using MySql.Data.MySqlClient;
using Mysqlx.Crud;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BST250301.Views
{
    public partial class ShowInit : UserControl
    {
        public bool submit;
        private string _msg = string.Empty;
        bool ret = false;
        /// <summary>
        ///自动关闭时为传入isAutoConfirm值
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="seconds"></param>
        /// <param name="isAutoConfirm"></param>
        public ShowInit(string msg)
        {
            InitializeComponent();
            this._msg = msg;
            this.listBox1.Items.Add(msg);
            this.buttonCancel.Enabled = false;
            Task.Delay(500);
            StartInit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            submit = false;
            this.Dispose();
        }
        private async Task<bool> StartInit()
        {
            try
            {
                await Task.Delay(200);
                //bool ret = false;
                SetLabelTxt("驱动端准备...");
                //驱动端准备
                ret = await Operation.StartOrStopEngineReady(true); 
                //ret = await Operation.GetEngineIsReady(); //判断PLC是否准备就绪(安全位状态)
                if (ret)
                {

                    SetLabelTxt($"驱动端准备就绪,开始初始化离合状态...");
                    await Task.Delay(200);
                    ret = await Operation.StartClutchInit();
                    if (ret)
                    {

                        SetLabelTxt($"初始化离合状态就绪,开始执行程序...");
                        await Task.Delay(500);
                    }
                    else
                    {
                        SetLabelTxt($"驱动端准备失败,请检查后再执行.");
                        await Task.Delay(500);
                    }
                }
                else
                {
                    SetLabelTxt($"驱动端准备失败,请检查后再执行.");
                    await Task.Delay(500);
                }
                if (ret)
                {
                    submit = true;
                    this.Dispose();
                    return true;
                }
            }
            catch (Exception ex)
            {
            }
            this.buttonCancel.Enabled = true;

            submit = false;
            return false;
        }
        private async Task SetLabelTxt(string text)
        {
            this.Invoke(new System.Windows.Forms.MethodInvoker(() =>
            {
                this.listBox1.Items.Add(text);
            }));
        }
    }
}
